using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class bullet : MonoBehaviour
{
    public bool canfllow;
    public float speed;
    public int damage;
    private Rigidbody2D rb;
    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    public void SetSpeed(Vector2 direction)
    {
        rb.velocity = direction.normalized * speed;
    }
    void Update()
    {
        if (canfllow)
        {
            if (Physics2D.OverlapCircle(transform.position, 4, LayerMask.GetMask("Enemy")))
            {
                transform.right = rb.velocity.normalized;
                Vector2 trans = FindClostaEnemy().transform.position - transform.position;
                rb.velocity = (rb.velocity * 4 + trans.normalized).normalized * speed;
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        //Destroy(gameObject);
        /*if (collision.gameObject.layer == LayerMask.NameToLayer("Enemy"))
        {
            collision.GetComponent<FSM>().Hurt(3);
        }*/
        ObjectPool.Instance.PushObject(gameObject);
    }
    public GameObject FindClostaEnemy()
    {
        GameObject closet = GameObject.FindWithTag("Enemy");
        if (GameObject.FindWithTag("Enemy") != null)
        {
            GameObject[] gos;
            gos = GameObject.FindGameObjectsWithTag("Enemy");
            float distance = Mathf.Infinity;
            foreach(GameObject go in gos)
            {
                Vector2 diff = go.transform.position - transform.position;
                float curDistance = diff.sqrMagnitude;
                if (curDistance < distance) { closet = go;distance = curDistance; }
            }
        }
        return closet;
    }
}
